import type { ApiRes } from '@/types/data'
import { useUserStore } from '@/store/user'
const store = useUserStore()
const BASEURL = import.meta.env.VITE_APP_BASEURL

interface RequestOption {
  url: string
  method?: 'GET' | 'POST' | 'DELETE' | 'PUT'
  header?: any
  data?: object
}
const request = <T>({
  url,
  method = 'GET',
  header = {},
  data = {}
}: RequestOption): Promise<ApiRes<T>> => {
  const token = store.user.token
  if (token) {
    // header.Authrozition = token
    header.token = token
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASEURL}${url}`,
      method,
      header,
      data,
      success: res => {
        if (res.statusCode === 401) {
          // 清空token
          store.setUser({})

          // 跳转到登录页面
          uni.reLaunch({
            url: '/subpkg/login/index'
          })

          return
        }
        // 返回给页面的是响应体的数据
        resolve(res.data as ApiRes<T>)
      },
      fail: error => {
        reject(error)
      }
    })
  })
}

export { request }
